<template>
  <el-container>
    <!-- 侧边树型 -->
    <el-aside v-show="asideVisible" class="aside-handle">
      <h2>组织架构树型目录</h2>
      <el-tree
        default-expand-all
        :expand-on-click-node="false"
        :data="manaTreeList"
        @node-click="treeClick"
      ></el-tree>
    </el-aside>
    <el-main>
      <!-- 表格  -->
      <vxe-grid
        ref="mainTable"
        column-key
        context-menu
        v-grid-drag-col
        :height="$store.getters.scrollerHeight()"
        :toolbar="tableToolbar"
        :columns="tableColumn"
        :proxy-config="tableProxy"
        pager-config
        :sort-config="{ remote: true }"
        :expand-config="{ lazy: true, loadMethod: expanded }"
      >
        <!-- 空数据渲染 -->
        <template v-slot:empty>
          <span style="color: red">
            <p>请先选择相应组织！</p>
          </span>
        </template>
        <!-- 多条件查询 -->
        <template v-slot:toolbar_search>
          <el-button
            icon="el-icon-s-operation"
            type="info"
            circle
            @click="asideVisible = !asideVisible"
          ></el-button>
          <rayd-multi-query
            v-model="queryEntity"
            @query="$refs[`mainTable`].commitProxy(`reload`)"
          >
            <vxe-form-item title="所属部门">
              <rayd-select :options="filtedDepTreeList" v-model="queryEntity.B_DepartmentId" tree-config/>
            </vxe-form-item>
            <vxe-form-item title="用户账号">
              <el-input v-model="queryEntity.B_Account"></el-input>
            </vxe-form-item>
            <vxe-form-item title="用户名称">
              <el-input v-model="queryEntity.B_RealName"></el-input>
            </vxe-form-item>
            <vxe-form-item title="创建日期">
              <rayd-date-picker
                type="datetimerange"
                v-model="queryEntity.B_CreateDate"
              ></rayd-date-picker>
            </vxe-form-item>
          </rayd-multi-query>
        </template>
        <!-- 业务按钮 -->
        <template v-slot:toolbar_buttons>
          <el-button
            round
            type="primary"
            icon="el-icon-plus"
            @click="handleAdd"
            v-permission-btn="'Add'"
            >新增</el-button
          >
          <el-button
            round
            type="warning"
            icon="el-icon-edit"
            @click="handleEdit"
            v-permission-btn="'Edit'"
            >编辑</el-button
          >
          <el-button
            round
            type="danger"
            icon="el-icon-delete"
            @click="handleDelete"
            v-permission-btn="'Delete'"
            >删除</el-button
          >
          <el-button
            round
            type="success"
            icon="el-icon-monitor"
            @click="handleAuthorize"
            v-permission-btn="'Authorize'"
            >分配权限</el-button
          >
          <exporter
            :exportConfig="{
              url: 'adminApi/User/Export',
              params: { queryjson: JSON.stringify(queryEntity) },
            }"
          />
          <importer
            :exportConfig="{
              url: 'adminApi/User/DownloadTemplate',
              params: {},
            }"
            :importConfig="{ url: 'adminApi/User/Import', params: {} }"
          />
          <el-divider direction="vertical"></el-divider>
        </template>
        <!-- 用户状态模板 -->
        <template v-slot:B_EnabledMark="{ row }">
          <vxe-switch
            v-model="row.B_EnabledMark"
            on-label="启用"
            :on-value="1"
            off-label="禁用"
            :off-value="0"
            @change="ChangeState(row)"
          ></vxe-switch>
        </template>
        <!-- 岗位/角色模板 -->
        <template v-slot:cellExpand="{ row }">
          <el-card>
            <el-form label-position="left" class="table-expand">
              <el-form-item label="岗位">
                <el-cascader
                  :props="{ multiple: true, ...$ELEMENT.cascaderProps }"
                  :show-all-levels="false"
                  :options="postTreeList"
                  :key="postKey"
                  v-model="row.postIds"
                  placeholder="无对应岗位"
                  :disabled="true"
                ></el-cascader>
              </el-form-item>
              <el-form-item label="角色">
                <rayd-select 
                  :options="roleList" 
                  :optionProps="{value:'B_RoleId', label:'B_FullName'}" 
                  v-model="row.roleIds" 
                  multiple 
                  placeholder="无对应角色"
                  :disabled="true"
                ></rayd-select>
              </el-form-item>
            </el-form>
          </el-card>
        </template>
      </vxe-grid>
    </el-main>
    <!-- 拟态窗口 -->
    <Form
      ref="mainForm"
      :manaId="B_ManaframeId"
      :depTreeList="filtedDepTreeList"
      @refresh="$refs[`mainTable`].commitProxy(`reload`)"
    />
    <!-- 分配权限 -->
    <Authorize ref="authorizeForm" :objectType="2" />
  </el-container>
</template>

<script>
import XEUtils from "xe-utils";

import {
  User,
  UserRelation,
  Role,
  Post,
  Department,
  Manaframe,
} from "@/api";
import importer from "@/components/ImportExcel";
import exporter from "@/components/ExportFile";
import Form from "./Form.vue";
import Authorize from "@/views/common/Authorize";
export default {
  components: {  importer, exporter, Form, Authorize },
  computed: {
    //过滤部门树型数据
    filtedDepTreeList() {
      return this.depTreeList.filter( item => item.B_ManaframeId === this.B_ManaframeId ) || [];
    },
    //列配置
    tableColumn() {
      return [
        {
          type: "seq",
          title: "序号",
          width: 50,
          align: "left",
        },
        { field: "B_Account", title: "账号", width: "100", sortable: true },
        { field: "B_RealName", title: "名称", width: "100", sortable: true },
        { field: "B_EnCode", title: "工号", width: "100", sortable: true },
        {
          field: "B_Gender",
          title: "性别",
          sortable: true,
          cellRender: {
            name: 'dataitem',
            code: "Gender" 
          },
          width: "100",
        },
        {
          field: "B_EnabledMark",
          title: "状态",
          sortable: true,
          slots: { default: "B_EnabledMark" },
          width: "100",
        },
        { 
          field: "B_DepartmentId",
          title: "所属部门", 
          cellRender: { name: 'department' },
          width: "250",
          sortable: true
        },
        {
          type: "expand",
          width: "85",
          title: "岗位/角色",
          slots: { content: "cellExpand" },
        },
        { field: "B_Description", title: "用户描述", width: "250", sortable: true },
        {
          field: "B_CreateDate",
          title: "创建日期",
          sortable: true,
          width: "100",
          formatter: ["toDateString", "yyyy-MM-dd"],
        },
      ]
    },
  },
  data() {
    return {
      /* 级联器Key */
      depKey: 1,
      postKey: 1,
      //侧边可见
      asideVisible: true,
      /* vxe-grid */
      queryEntity: {}, //查询实体
      //工具栏配置
      tableToolbar: {
        refresh: true,
        zoom: true,
        custom: true,
        
      },
      //数据代理配置
      tableProxy: {
        seq: true, // 启用动态序号代理
        sort: true, // 启用排序代理
        autoLoad: false, //是否自动加载查询数据
        ajax: {
          // 任何支持 Promise API 的库都可以对接（fetch、jquery、axios、xe-ajax）
          query: ({ page, sort, filters }) => {
            //选中了组织架构才可以查询
            if (this.util.validateNull(this.B_ManaframeId)) {
              this.$message.warning("请先选择相应组织架构！");
              return;
            }
            page.sidx = sort.property;
            page.sord = sort.order;
            return User.GetPageList({
              queryjson: JSON.stringify(Object.assign({ B_ManaframeId : this.B_ManaframeId }, this.queryEntity)),
              pagination: JSON.stringify(page),
            }).then((res) => {
              return res;
            });
          },
        },
      },
      /* 实体数据 */
      B_ManaframeId: "", //选中的组织架构
      manaTreeList: [], //组织树型数据
      depTreeList: [], //部门树型数据
      postTreeList: [], //岗位树型数据
      roleList: [], //角色列表数据
    };
  },
  //级联器重新渲染
  watch: {
    depTreeList(newValue, oldValue) {
      ++this.depKey;
    },
    postTreeList(newValue, oldValue) {
      ++this.postKey;
    },
  },
  created() {
    //初始化
    this.init();
  },
  methods: {
    //初始化
    init() {
      this.$store.commit("SET_ISLOADING",true);

      /* 初始化数据源 */
      Promise.all([
        //获取组织树形数据
        Manaframe.GetTreeList().then((res) => {
          this.manaTreeList = res;
        }),
        //获取部门树形数据
        Department.GetTreeList({
          B_ManaframeId: "",
          isDeep: false,
        }).then((res) => {
          this.depTreeList = res;
        }),
        //获取岗位树形数据
        Post.GetTreeList({
          B_ManaframeId: "",
          B_DepartmentId: "",
          isDeep: true,
        }).then((res) => {
          this.postTreeList = res;
        }),
        //获取角色列表数据
        Role.GetListByManaId({ B_ManaframeId: "", isDeep: true }).then(
          (res) => {
            this.roleList = res;
          }
        ),
      ]).then(() => {
        this.$store.commit("SET_ISLOADING",false);
      });
    },
    //树型目录单机回调
    treeClick(node, Node, selfCom) {
      this.B_ManaframeId = node.id; //存储选择节点
      this.queryEntity.B_DepartmentId = ""; //清空部门下拉
      this.$refs["mainTable"].commitProxy("reload"); // 刷新表格
    },
    //状态变更
    ChangeState(row) {
      User.ChangeState({
        B_UserId: row.B_UserId,
        B_EnabledMark: row.B_EnabledMark,
      }).catch((err) => {
        //状态归位
        row.B_EnabledMark = !row.B_EnabledMark;
      });
    },
    //行展开回调
    expanded({ row }) {
      return UserRelation.GetObjIdList(row.B_UserId).then((res) => {
        row.postIds = res.postIdList;
        row.roleIds = res.roleIdList;
      });
    },
    //新增
    handleAdd() {
      //选中了组织架构才可以打开
      if (this.util.validateNull(this.B_ManaframeId)) {
        this.$message.warning("请先选择相应组织架构！");
        return;
      }
      this.$refs["mainForm"].formOpen();
    },
    //编辑
    handleEdit() {
      let row = this.$refs["mainTable"].getCurrentRecord();
      if (row) {
        this.$refs["mainForm"].formOpen(row);
      }else{
        this.$message.warning("请选择数据行！");
      }
    },
    //删除
    handleDelete() {
      let row = this.$refs["mainTable"].getCurrentRecord();
      if (row) {
        this.$confirm("确认永久删除该行数据?", "提示", { type: "warning" })
          .then(() => {
            User.Delete(row).then((res) => {
              this.$refs["mainTable"].commitProxy("reload"); // 刷新表格
            });
          })
          .catch((e) => {});
      }else{
        this.$message.warning("请选择数据行！");
      }
    },
    //分配权限
    handleAuthorize() {
      let row = this.$refs["mainTable"].getCurrentRecord();
      if (row) {
        this.$refs["authorizeForm"].formOpen(row.B_UserId);
      }else{
        this.$message.warning("请选择数据行！");
      }
    },
  },

};
</script>

<style lang="less" scoped>
.vxe-body--expanded-cell {
  white-space: inherit;
}
.table-expand {
  font-size: 0;
}
.table-expand label {
  width: 90px;
  color: #99a9bf;
}
.table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 100%;
}
</style>